package bjut.core.compress;

import bjut.core.interfaces.Compress;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * @Author: zhuzhiming
 * @Date: 2022/4/13 0:45
 */
public class GzipCompress implements Compress {

    private static final int BUFFER_SIZE = 4 * 1024;

    @Override
    public byte[] compress(byte[] bytes) {

        if (bytes == null) {
            throw new NullPointerException("compress bytes is null");
        }
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
            gzipOutputStream.write(bytes);
            gzipOutputStream.flush();
            gzipOutputStream.close();
            gzipOutputStream.finish();
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("gzip compress fail");
        }

    }

    @Override
    public byte[] decompress(byte[] bytes) {

        if (bytes == null) {
            throw new NullPointerException("decompress bytes is null");
        }
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
            byte[] buffer = new byte[BUFFER_SIZE];
            int len;
            while ((len = gzipInputStream.read(buffer)) > -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("decompress fail");
        }
    }
}
